package tools.solid;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;

public class solidUtils {

	public static void main(String[] args) throws Exception{

		if(args.length>0){
			if(args[0].equals("extractFrequencies")&&args.length==3){
				extractFrequencies(args[1],args[2]);
			}else if(args[0].equals("other")&&args.length==2){
					//other method
				}else{
				System.err.println(printHelp());
				System.exit(616);
			}
		}else{
			System.err.println(printHelp());
			System.exit(616);
		}
	}

	private static String printHelp(){
		String help="Usage: solidUtils <cmd> <input>\n";
		help+="where <cmd> is:\n";
		help+="extractFrequencies - Takes a snps.txt file and a corresponding gff file (i.e F3_annotated.gff) and extracts the frequencies for the nucleotides\n";
		help+="\t<input> = <snps.txt> <gff file>\n";
		
		
		
		return help;
	}
	
	public static void extractFrequencies(String snpsFile, String gffFile)throws Exception{
		BufferedReader in= new BufferedReader(new FileReader(snpsFile));
		String firstLine= in.readLine();
		HashMap<Integer, String> lines= new HashMap<Integer, String>();
		HashMap<Integer, HashMap<String, Integer>> counts= new HashMap<Integer, HashMap<String,Integer>>();
		int start, stop;
		String[] l;
		String[] nucleotides =new String[] {"A","C","G","T","a","c","g","t","N","n"};
		String seq,c;
		for(String s=in.readLine();s!=null;s=in.readLine()){
			l =s.split("\t");
			if(l.length>=12){
				lines.put(Integer.parseInt(l[11]), s);
				HashMap<String, Integer> hm= new HashMap<String, Integer>();
				for (String nuc : nucleotides) {
					hm.put(nuc, 0);
				}
				counts.put(Integer.parseInt(l[11]), hm);
			}
		}
		in= new BufferedReader(new FileReader(gffFile));
		for(String s= in.readLine();s!=null;s=in.readLine()){
			l= s.split("\t");
			if(l.length==9){
				start=Integer.parseInt(l[3]);
				stop=Integer.parseInt(l[4]);
				for (Integer snp : counts.keySet()) {
					if(snp+1>=start &&snp+1<=stop){
						seq=l[8].split(";")[0].split("=")[1];
						c=seq.substring(snp-start+1, snp-start+2);
						if(l[6].equals("-")){
							
						}
						if(!counts.get(snp).containsKey(c)){
							System.err.println("fck: "+c);
						}
//						System.err.println(c);
						counts.get(snp).put(c, counts.get(snp).get(c)+1);
					}
				}
			}
		}
		for (String nuc : nucleotides) {
			firstLine+="\t"+nuc;
		}
		System.out.println(firstLine);
		for (Integer snp : counts.keySet()) {
			c=lines.get(snp);
			for (String nuc : nucleotides) {
				c+="\t"+counts.get(snp).get(nuc);
			}
			System.out.println(c);
		}
	}
}
